package com.dyh.quickdemo.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/*
@Author=Joey Wheeler
@Date=2021/3/29 11:27
*/
public class JavaLocalBizLockV2 {
    private static  volatile  ConcurrentHashMap<String,Long> lockMap = new ConcurrentHashMap<>();
//    {
//        Thread thread = new Thread(()->{
//            for (String key : lockMap.keySet()) {
//                if (lockMap.get(key)!=null&&lockMap.get(key)){
//                }
//            }
//        },"JavaLocalBizLockV2Clear");
//        thread.setDaemon(true);
//    }

   private static Logger logger = LoggerFactory.getLogger(JavaLocalBizLockV2.class);

    public static boolean tryLock(String bizKey,long time) throws InterruptedException {
        Long res = lockMap.putIfAbsent(bizKey,time);
        return res!=null && res == time;
    }

    public static void unlock(String bizKey){
        lockMap.remove(bizKey);
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            try {
                logger.info("{} {}",
                        Thread.currentThread().getName(),
                        JavaLocalBizLockV2.tryLock("hello",100L));
                Thread.sleep(500L);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                JavaLocalBizLockV2.unlock("hello");
            }
        }).start();




        new Thread(()->{
            try {
                logger.info("{} {}",
                        Thread.currentThread().getName(),
                        JavaLocalBizLockV2.tryLock("hello",100L));
                Thread.sleep(500L);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                JavaLocalBizLockV2.unlock("hello");
            }
        }).start();
    }
}
